package service;

import model.Paper;
import model.Student;
import service.visitor.PaperSelectionVisitor;

import java.util.*;

public class PaperSelection {
    private final Map<Paper, Student> selections = new HashMap<>();
    
    public boolean addSelection(Student student, Paper paper) {
        // 防止重复选择同一篇论文
        if (selections.containsKey(paper)) {
            return false;
        }
        
        // 防止学生重复选择
        if (isStudentAlreadySelected(student)) {
            throw new IllegalStateException("学生 " + student.getName() + " 已选择过论文");
        }
        
        selections.put(paper, student);
        return true;
    }
    
    public boolean isSelected(Paper paper) {
        return selections.containsKey(paper);
    }
    
    public boolean isStudentAlreadySelected(Student student) {
        for (Student s : selections.values()) {
            if (s.equals(student)) {
                return true;
            }
        }
        return false;
    }
    
    public void accept(PaperSelectionVisitor visitor) {
        visitor.visit(this);
    }
    
    public Map<Paper, Student> getSelections() {
        return Collections.unmodifiableMap(selections);
    }
    
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<Paper, Student> entry : selections.entrySet()) {
            sb.append(entry.getKey().toString())
              .append("\t selected by ")
              .append(entry.getValue().getName())
              .append("\n");
        }
        return sb.toString();
    }
}
